package com.tools.web.work.excel.easyexcel;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import com.tools.common.object.Note;
import com.tools.web.work.excel.poi.ExcelKit;
import com.tools.web.work.excel.poi.MergeCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.List;
import java.util.Map;

/**
 * EasyExcel 用于合并单元格的策略处理器
 * */
@Note("EasyExcel 用于合并单元格的策略处理器")
public class EasyExportMergeStrategy implements RowWriteHandler {

    @Note("合并单元格索引记录容器")
    private final Map<Object, List<MergeCell>> mergeCellIndexMap;

    public EasyExportMergeStrategy(Map<Object, List<MergeCell>> mergeCellIndexMap) {
        this.mergeCellIndexMap = mergeCellIndexMap;
    }

    @Override
    public void afterRowDispose(RowWriteHandlerContext context) {
        Sheet sheet = context.getWriteSheetHolder().getSheet();
        Integer rowIndex = context.getRowIndex();
        Row row = context.getRow();
        for (int i = 0; i <= row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            String val = (cell == null) ? null : cell.toString();
            String prefix = rowIndex + "-" + i;
            ExcelKit.recordMergeRowIndex(this.mergeCellIndexMap, rowIndex, i, prefix, val);
        }
        if(this.mergeCellIndexMap != null && !this.mergeCellIndexMap.isEmpty()) {
            ExcelKit.defaultMergeTableHandle(this.mergeCellIndexMap, sheet);
        }
    }
}
